package com.sneakxy.mybase4j.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
import org.springframework.web.servlet.support.RequestContext;

public class MyBase4jHandlerExceptionResolver extends AbstractHandlerExceptionResolver {
	
	protected final Logger log = LogManager.getLogger(this.getClass());
	
	private View defaultView;
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception e) {
		RequestContext requestContext = new RequestContext(request);
		ModelAndView result = new ModelAndView(this.getDefaultView());
		int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
		int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
		String message = e.getLocalizedMessage();
		//未认证
        if(e instanceof UnauthenticatedException) {
        	code = HttpServletResponse.SC_UNAUTHORIZED;
        } else if(e instanceof UnauthorizedException) {
        	//没有权限
        	code = HttpServletResponse.SC_FORBIDDEN;
        } else if(e instanceof MaxUploadSizeExceededException) {
        	//上传文件过大
        	message = requestContext.getMessage("upload.file.size.message");
        	status = HttpServletResponse.SC_OK;
        } else {
        	this.log.error("异常捕捉：", e);
        }
        response.setStatus(status);
        
        result.addObject("success", false);
        result.addObject("code", code);
        result.addObject("message", message);
        return result;
	}

	public View getDefaultView() {
		return defaultView;
	}

	public void setDefaultView(View defaultView) {
		this.defaultView = defaultView;
	}

}
